package com.lwj.liwanjia.view.activity.myindent.tuikuantuihuo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.AddAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.IndentDetailBean;
import com.lwj.liwanjia.bean.ShenqinBean;
import com.lwj.liwanjia.bean.UrlBean;
import com.lwj.liwanjia.impl.ShenqinView;
import com.lwj.liwanjia.impl.UrlView;
import com.lwj.liwanjia.presenter.ShenqingPrensenter;
import com.lwj.liwanjia.presenter.UrlPresenter;
import com.lwj.liwanjia.utils.BitmapUtils;
import com.lwj.liwanjia.utils.InputImageDialog;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.TuihuoDialog;
import com.lwj.liwanjia.view.activity.myindent.ReturnActivity;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import retrofit2.Retrofit;

public class TuiKuanDetailActivity extends BaseActivity implements ShenqinView, UrlView {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_shangpin)
    ImageView ivShangpin;
    @BindView(R.id.tv_shangpin)
    TextView tvShangpin;
    @BindView(R.id.tv_jianjie)
    TextView tvJianjie;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_huowu_state)
    TextView tvHuowuState;
    @BindView(R.id.tv_tuikuan_yunayin)
    TextView tvTuikuanYunayin;
    @BindView(R.id.rl_state)
    RelativeLayout rlState;//退货状态
    @BindView(R.id.tv_tuikuan_money)
    TextView tvTuikuanMoney;
    @BindView(R.id.tv_tuikuan_shuoming)
    EditText tvTuikuanShuoming;
    @BindView(R.id.rl_pingzheng)
    SuperRecyclerView rlPingzheng;
    @BindView(R.id.tv_num)
    TextView tvNum;

    private AddAdapter addAdapter;
    private List<String> list = new ArrayList<>();
    private List<String> dialogList = new ArrayList<>();
    private String tradeId;
    private IndentDetailBean.DataBean.CommodityBean commodity;
    private ShenqingPrensenter presenter;
    private String token;
    private Map<String, Object> map = new HashMap<>();
    private String type;
    private InputImageDialog imageDialog;
    private View footerView;
    private List<File> files = new ArrayList<>();
    private UrlPresenter urlPresenter;//上传图片
    private ImageView add;

    @Override
    protected void initView() {
        tvLeft.setVisibility(View.VISIBLE);
        Intent intent = getIntent();
        tradeId = intent.getStringExtra("tradeId");
        commodity = (IndentDetailBean.DataBean.CommodityBean) intent.getSerializableExtra("goods");
        type = intent.getStringExtra("type");
        if (type.equals("仅退款")) {
            rlState.setVisibility(View.VISIBLE);
            tvTitle.setText("申请退款");
        } else {
            rlState.setVisibility(View.GONE);
            tvTitle.setText("申请退货退款");
        }
        if (tradeId != null) {
            Glide.with(this).load(commodity.getCommodityimage()).error(R.mipmap.tupian).into(ivShangpin);
            tvShangpin.setText(commodity.getCommodityname());
            tvJianjie.setText(commodity.getCommodityinfo());
            tvPrice.setText("￥" + commodity.getCommodityprice());
            tvNum.setText("*" + commodity.getCommodityNum());
            tvTuikuanMoney.setText("￥" + commodity.getCommodityprice());
        }
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        rlPingzheng.setLayoutManager(manager);
        rlPingzheng.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = getResources().getDimensionPixelOffset(R.dimen.x10);
                outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.x10);
            }
        });
        rlPingzheng.setRefreshEnabled(false);
        rlPingzheng.setLoadMoreEnabled(false);
        addAdapter = new AddAdapter(this, list);
        addView();
        rlPingzheng.setAdapter(addAdapter);
        presenter = new ShenqingPrensenter(this);
        urlPresenter = new UrlPresenter(this);
        token = SpfUtils.getSpfUtils(this).getToken();
        listener();
    }

    private void listener() {
        addAdapter.setOnItemChildClickListener(new SuperBaseAdapter.OnRecyclerViewItemChildClickListener() {
            @Override
            public void onItemChildClick(SuperBaseAdapter adapter, View view, int position) {
                list.remove(position);
                if (list.size() < 3) {
                    add.setVisibility(View.VISIBLE);
                }
                addAdapter.notifyDataSetChanged();
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            //照相
            if (requestCode == InputImageDialog.CAMERA_REQUEST_CODE) {
                String imagePath = imageDialog.cameraPath;
                if (list.size() < 3) {
                    list.add(imagePath);
                }
                if (list.size() == 3) {
                    add.setVisibility(View.GONE);
                }
            } else if (requestCode == InputImageDialog.ALBUM_REQUEST_CODE) {//相册
                ArrayList<String> imageUrl = data.getStringArrayListExtra("imageUrl");
                for (int i = 0; i < imageUrl.size(); i++) {
                    if (list.size() < 3) {
                        list.add(imageUrl.get(i));
                    }
                    if (list.size() == 3) {
                        add.setVisibility(View.GONE);
                    }
                }
            }
            addAdapter.notifyDataSetChanged();
        }
    }

    private void addView() {
        footerView = LayoutInflater.from(this).inflate(R.layout.add_item, null);
        add = (ImageView) footerView.findViewById(R.id.iv_add);
        addAdapter.addFooterView(footerView);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageDialog = new InputImageDialog(TuiKuanDetailActivity.this);
                imageDialog.show();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tui_kuan_detail;
    }

    @OnClick({R.id.tv_left, R.id.rl_state, R.id.rl_yuanyin, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.rl_state://货物状态
                dialogList.clear();
                dialogList.add("未收到货");
                dialogList.add("已收到货");
                TuihuoDialog dialog = new TuihuoDialog(TuiKuanDetailActivity.this, tvHuowuState, "货物状态", dialogList);
                dialog.show();
                break;
            case R.id.rl_yuanyin://退款原因
                dialogList.clear();
                dialogList.add("7天无理由退换货");
                dialogList.add("商品存在瑕疵");
                dialogList.add("商品存在破损");
                dialogList.add("商品与描述不符合");
                dialogList.add("个人原因");
                TuihuoDialog dialog1 = new TuihuoDialog(TuiKuanDetailActivity.this, tvTuikuanYunayin, "退款原因", dialogList);
                dialog1.show();
                break;
            case R.id.tv_submit:
                map.put("token", token);
                map.put("afterSaleType", type);//售后类型
                if (type.equals("仅退款")) {
                    map.put("afterSaleGoodType", tvHuowuState.getText().toString());//货物状态
                    if (TextUtils.isEmpty(tvHuowuState.getText().toString())) {
                        Toast.makeText(this, "货物状态不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (TextUtils.isEmpty(tvTuikuanYunayin.getText().toString())) {
                    Toast.makeText(this, "申请原因不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                map.put("afterSaleReson", tvTuikuanYunayin.getText().toString());//原因
                map.put("afterSaleMoney", tvTuikuanMoney.getText().toString());//金额
                map.put("tradeId", tradeId);
                //退款说明
                if (!TextUtils.isEmpty(tvTuikuanShuoming.getText().toString())) {
                    map.put("afterSaleExplain", tvTuikuanShuoming.getText().toString());
                }
                for (int i = 0; i < list.size(); i++) {
                    String imageUrl = list.get(i);
                    String fileName = System.currentTimeMillis() + ".png";
                    BitmapUtils.compressImageByPixel(imageUrl, fileName);
                    File file = new File(Constants.IMAGE_PATH + fileName);
                    files.add(file);
                }
                if (files.size() > 0) {
                    urlPresenter.urlIndent(files, token);
                } else {
                    presenter.shenqingIndent(map);
                }
                break;
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "访问网络失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void inputIamge(UrlBean urlBean) {
        if (urlBean.getState() == 0) {
            Toast.makeText(this, "申请失败", Toast.LENGTH_SHORT).show();
        } else if (urlBean.getState() == 1) {
            if (!TextUtils.isEmpty(urlBean.getData().getUrl())) {
                map.put("afterSalePic", urlBean.getData().getUrl());
                presenter.shenqingIndent(map);
            }
        }
    }

    @Override
    public void shenqinIndent(ShenqinBean shenqinBean) {
        if (shenqinBean.getState() == 0) {
            Toast.makeText(this, "申请失败", Toast.LENGTH_SHORT).show();
        } else if (shenqinBean.getState() == 1) {
            if (shenqinBean.getData().getStatus().equals("申请成功")) {
                Toast.makeText(this, "申请" + type + "成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, ReturnActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter = null;
        }
        if (urlPresenter != null) {
            urlPresenter = null;
        }
    }
}
